import Vue from 'vue';
import Vuex from 'vuex';
import request from '../common/request.js';
import wallet from "../common/wallet";

Vue.use(Vuex);
const store = new Vuex.Store({
    state: {
        isLogin: false,
        account: "",
        usdtaddress: "0x55d398326f99059fF775485246999027B3197955",
        random: 0
    },
    // 修改store中的值唯一的方法就是提交mutation来修改
    mutations: {
        /**
         * 设置状态
         * @param {Object} state 状态对象
         * @param {Object} provider 传入值
         */
        accountState(state, provider) {
            state.account = provider
        },
        isLoginState(state, provider) {
            state.isLogin = provider
        },
    },
    actions: {
        // 检测钱包环境
        async initWeb3(context) {
            let address = await wallet.getAddress();
            console.log("获取钱包地址", address)
            let account = uni.getStorageSync("address") || ""
            console.log("获取缓存钱包地址", account)
            if (address === account) {
                context.commit("accountState", account);
                context.commit("isLoginState", true);
                context.state.random = Math.random()
                return
            }
            request("/front/getLoginCode", {
                address: address
            }).then(res => {
                if (res.code === 0) {
                    wallet.getSigner().signMessage(res.data).then(res => {
                        request("/front/login", {
                            address: address,
                            signature: res
                        }).then(logRes => {
                            if (logRes.code === 0) {
                                uni.setStorageSync("token", logRes.data);
                                uni.setStorageSync("address", address);
                                context.commit("accountState", address);
                                context.commit("isLoginState", true);
                                context.state.random = Math.random()
                            } else {
                                uni.showToast({
                                    title: logRes.msg,
                                    icon: "none"
                                })
                            }
                        })
                    })
                }
            })
        },
    }
})

export default store
